<?php
/**
 * Created by PhpStorm.
 * User: czw
 * Date: 2018/7/11
 * Time: 14:59
 */
namespace app\common\model;


use app\lib\exception\BaseException;
use app\lib\exception\DeleteException;
use app\lib\exception\NotFoundException;
use think\Db;
use think\Model;

class Permission extends Model
{
    /**
     * 新增permission权限
     * @param $data
     * @return false|int
     */
    public static function createOne($data)
    {
        $model = new self();
        $permission = $model->where(['role_id' => $data['role_id'],'source_id'=>$data['source_id'],'action'=>$data['action']])->find();
        $source = Db::table(config('database.prefix').'source')->where('id='.$data['source_id'])->field('identity')->find();
        if(!$source) throw new BaseException(['msg'=>'要绑定的资源不存在！']);
        $data['source_identity'] = $source['identity'];
        if ($permission) throw new BaseException(['msg' => '权限已存在！请勿重复创建']);
        $res = $model->allowField(true)->save($data);
        if(!$res) throw (new BaseException());//创建失败，经过验证的数据不能正确保存，只能报系统异常
        return $res;
    }


    public static function deleteOne($id)
    {
        $auth = self::find($id);
        if (!$auth) throw (new NotFoundException());
        $res = self::destroy($id);
        if(!$res) throw (new DeleteException());
    }
}